import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { BlogService } from 'src/blog/blog.service';
import { Repository } from 'typeorm';
import { Comment } from './comment.entity';
import { CommentDto } from './dto/comment.dto';

@Injectable()
export class CommentService {
    constructor(
        @InjectRepository(Comment)
        private readonly commentRepo: Repository<Comment>,
        private readonly blogService: BlogService
    ) { }

    async saveComment(newComment: CommentDto) {
        const addedComment = new CommentDto()
        addedComment.nickName = newComment.nickName
        addedComment.email = newComment.email
        addedComment.content = newComment.content
        //写死
        addedComment.avatar = '/images/visitor.png'
        addedComment.blogId = newComment.blogId
        addedComment.blog = await this.blogService.getBlogById(newComment.blogId)
        //判断是否是管理员
        if(addedComment.nickName === '张童瑶' && addedComment.email === 'mySecret@163.com'){
            addedComment.adminComment = true
            addedComment.avatar = '/images/avatar.jpg'
        }
        if (newComment.parentCommentId !== -1) {
            addedComment.parentComment = await this.getCommentById(newComment.parentCommentId)
        } else {
            addedComment.parentComment = null
        }
        try {
            await this.commentRepo.save(addedComment)
        } catch (error) {
            throw new Error('评论保存失败！' + error)
        }
        return this.getAllCommentsByBlogId(newComment.blogId)
    }

    async getCommentById(commentId) {
        return await this.commentRepo.findOne(commentId)
    }

    async getReplyCommentById(commentId) {
        return await this.commentRepo.find({
            where: {
                id: commentId
            },
            relations: ['replyComments']
        })
    }

    async getAllCommentsByBlogId(blogId: number) {
        const comments = await this.commentRepo.find({
            where: {
                blogId: blogId,
                parentCommentId: null
            },
            relations: ['replyComments'],
            order: {
                createTime: 'DESC'
            }
        })
        //console.log(comments)
        //return comments
        return this.eachComment(comments)
    }

    //循环每个顶级的评论节点
    async eachComment(comments: Comment[]) {
        //深拷贝comments数组
        let commentsRoot = JSON.parse(JSON.stringify(comments))
        //合并评论的各层子代到第一级子代集合中
        return this.combineChildren(commentsRoot)
    }

    //
    async combineChildren(comments: Comment[]) {
        for (let comment of comments) {
            //查询回复的评论
            //console.log(comment)
            const replys = (await this.getReplyCommentById(comment.id))[0].replyComments
            //循环
            for (let reply of replys) {
                await this.recursively(reply)
            }
            //修改顶级节点的reply集合为迭代处理后的集合
            comment.replyComments = [...new Set(this.temReplys)]
            //console.log(comment)
            //清除临时存放区
            this.temReplys = []
        }
        return comments
    }

    //存放迭代找出的所有子代的集合
    temReplys = []

    //迭代递归
    async recursively(comment: Comment) {
        //console.log(comment)
        this.temReplys.push(comment)
        //console.log(this.temReplys)
        let replys = (await this.getReplyCommentById(comment.id))[0].replyComments
        if (replys.length > 0) {
            for (let reply of replys) {
                //console.log(reply)
                this.temReplys.push(reply)
                let tempLength = (await this.getReplyCommentById(reply.id))[0].replyComments.length
                if (tempLength > 0) {
                    await this.recursively(reply)
                }
            }
        }
        //console.log(this.temReplys)
    }
}
